const router = require('koa-router')()

const {Resolve} = require('../../lib/helper');
const res = new Resolve();
// redis key 前缀
const REDIS_KEY_API_PREFIX = 'boblog_api'
const {ProjectController} = require('../../controller/project')
const {ProjectValidator,ProjectIdParamsValidator,ProjectSearchValidator} = require('../../validators/project');
const { Project } = require('../../models/project');
const {getRedis, setRedis} = require('../../cache/_redis.js')
router.prefix('/api/v1')

/**
 * 创建项目
 */

router.post('/project', async (ctx) => {
    // 通过验证器校验参数是否通过
    const v = await new ProjectValidator().validate(ctx);
 
    // 创建项目
    const r =  await ProjectController.create(v);
    console.log(r)
    // 返回结果
    ctx.response.status = 200;
    ctx.body = res.success('创建项目成功');
   // ctx.body = res.json(r);
});
/**
 * 获取项目列表
 */
router.get('/projectList',async (ctx) => {
    // 尝试获取项目缓存
    const {page = 1} = ctx.query;
    const key = `${REDIS_KEY_API_PREFIX}_project_list_id_page${page}`
    const projectList = await ProjectController.list(ctx.query)

    const cacheProjectData = await getRedis(key)

    if (cacheProjectData) {
      ctx.body = res.json(cacheProjectData);
  
    } else {
          setRedis(key, projectList, 60)
            ctx.response.status = 200
            // 设置缓存，过期时间1min
            ctx.body = res.json(projectList)
    }
})

/**
 * 编辑项目
 */


/**
 * 删除项目
 */
router.delete('/project/:id',async(ctx)=>{
    // 通过验证器校验参数是否通过
    const v = await ProjectIdParamsValidator().validate(ctx);
     // 获取ID参数
     const id = v.get('path.id')
     // 删除
     await ProjectController.destroy(id)
     ctx.response.status = 200;
     ctx.body = res.success('删除文章成功');
})

/**
 * 搜索项目
 */


/**
 * 项目详情
 */

 module.exports = router